package org.apache.ibatis.demo;

import org.apache.ibatis.demo.mapper.BlogMapper;
import org.apache.ibatis.demo.pojo.Blog;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisMain {
  private SqlSessionFactory getSqlSessionFactory() throws IOException {
    String resource = "org/apache/ibatis/demo/mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    return sqlSessionFactory;
  }

  @Test
  public void testFirstLevelCache() throws IOException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession session = sqlSessionFactory.openSession();
    BlogMapper mapper = session.getMapper(BlogMapper.class);
    Blog blog = mapper.selectBlog(1);

    BlogMapper mapper2 = session.getMapper(BlogMapper.class);
    Blog blog2 = mapper2.selectBlog(1);
    System.out.println("一级缓存：" + (blog == blog2));
  }

  @Test
  public void testSecondLevelCache() throws IOException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession session = sqlSessionFactory.openSession();
    BlogMapper mapper = session.getMapper(BlogMapper.class);
    Blog blog = mapper.selectBlog(1);
    session.close();

    SqlSession session2 = sqlSessionFactory.openSession();
    BlogMapper mapper2 = session2.getMapper(BlogMapper.class);
    Blog blog2 = mapper2.selectBlog(1);
    System.out.println("二级缓存：" + (blog == blog2));
  }
}
